<?php

namespace app\admin\validate\crontab;

use tmcore\base\BaseValidate;
use tmcore\services\CronExpressionService;

/**
 * 定时任务验证器
 */
class CrontabValidate extends BaseValidate
{
    protected $rule = [
        'name' => 'require',
        'command' => 'require',
        'status' => 'require|in:1,2,3',
        'expression' => 'require|checkExpression',
        'id' => 'require',
        'operate' => 'require',
    ];

    protected $message = [
        'name.require' => '请输入定时任务名称',
        'command.require' => '请输入命令',
        'status.require' => '请选择状态',
        'status.in' => '状态值错误',
        'expression.require' => '请输入运行规则',
        'id.require' => '参数缺失',
        'operate.require' => '请选择操作',
    ];


    /**
     * 添加定时任务场景
     * @return CrontabValidate
     */
    public function sceneAdd()
    {
        return $this->remove('id', 'require')->remove('operate', 'require');
    }


    /**
     * 查看定时任务详情场景
     * @return CrontabValidate
     */
    public function sceneDetail()
    {
        return $this->only(['id']);
    }


    /**
     * 编辑定时任务
     * @return CrontabValidate
     */
    public function sceneEdit()
    {
        return $this->remove('operate', 'require');
    }


    /**
     * 删除定时任务场景
     * @return CrontabValidate
     */
    public function sceneDelete()
    {
        return $this->only(['id']);
    }


    /**
     * 操作定时任务场景
     * @return CrontabValidate
     */
    public function sceneOperate()
    {
        return $this->only(['id', 'operate']);
    }


    /**
     * 获取规则执行时间场景
     * @return CrontabValidate
     */
    public function sceneExpression()
    {
        return $this->only(['expression']);
    }


    /**
     * 校验运行规则
     * @param $value
     * @param $rule
     * @param $data
     * @return bool|string
     */
    public function checkExpression($value, $rule, $data)
    {
        if(!(isset($data['expression']['type']) && in_array($data['expression']['type'], [1,2,3,4,5,6,7,8]))) return '定时任务运行规则类型错误';

        if(!empty($data['name'])) {
            $cronExpressionService = (new CronExpressionService);
            $expression = $cronExpressionService->getCronExpression($data['expression']['type'], $data['expression']);
            if ($cronExpressionService->verifyExpression($expression) === false) {
                throw new \Exception('定时任务运行规则错误');
            }
        }

        return true;
    }
}